/* Copyright 2013-2015 www.snakerflow.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.snaker.engine.spring;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snaker.engine.Context;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;

/**
 * spring的服务查找实现
 * 
 * @author yuqs
 * @since 1.5
 */
public class SpringContext implements Context {
    private static final Logger log = LoggerFactory.getLogger(SpringContext.class);

    /**
     * find
     */
    public <T> T find(Class<T> clazz) {
        T result = null;
        try {
            result = SpringUtil.getBean(clazz);
        } catch (Exception e) {
            log.debug("没有找到对应的bean：" + clazz);
        }
        return result;
    }

    /**
     * findList
     */
    public <T> List<T> findList(Class<T> clazz) {
        List<T> beans = new ArrayList<T>();
        try {
            Map<String, T> maps = SpringUtil.getBeansOfType(clazz);
            if (maps != null && maps.size() > 0) {
                beans = ListUtil.toList(maps.values());
            }
        } catch (Exception e) {
            log.debug("没有找到对应的bean：" + clazz);
        }
        return beans;
    }

    /**
     * findByName
     */
    public <T> T findByName(String name, Class<T> clazz) {
        T result = null;
        try {
            result = SpringUtil.getBean(name, clazz);
        } catch (Exception e) {
            log.debug("没有找到对应的bean：" + clazz);
        }
        return result;
    }

    /**
     * put
     */
    // public void put(String name, Object object) {
    // SpringUtil.registerBean(name, object);
    // }

    /**
     * 向spring添加bean的定义
     */
    public void put(String name, Class<?> clazz) {
        SpringUtil.registerBean(name, ReflectUtil.newInstance(clazz));
    }

    /**
     * 判断是否存在服务
     */
    public boolean exist(String name) {
        boolean result = false;
        try {
            result = SpringUtil.getBean(name) != null;
        } catch (Exception e) {
            log.debug("没有找到对应的bean：" + name);
        }
        return result;
    }
}
